package com.fansl.koala.quickdev.common.utils;

import java.util.Random;

/**
 * @author fansl
 * @Description: TODO
 * @date 2020/4/7 10:54
 */
public class TokenBucket {
    // 当前时间
    public long timeStamp = System.currentTimeMillis();
    // 桶的容量
    public long capacity;
    // 令牌放入速度
    public long rate;
    // 当前令牌数量
    public long tokens;

    public boolean grant() {
        long now = System.currentTimeMillis();
        // 先添加令牌
        tokens = Math.min(capacity, tokens + (now - timeStamp) * rate);
        timeStamp = now;
        if (tokens < 1) {
            // 若不到1个令牌,则拒绝
            return false;
        } else {
            // 还有令牌，领取令牌
            tokens -= 1;
            return true;
        }
    }
    public static void main(String[] args) {
         TokenBucket tokenBucket = new TokenBucket();
         tokenBucket.capacity = 1;
        tokenBucket.rate = 2;
        while (true){
            if(tokenBucket.grant()){
                System.out.println("获取到令牌");
            }else {
                System.out.println("未取到令牌");
            }
            try {
                Thread.sleep(new Random().nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
